<?php
/**
 * Created by PhpStorm.
 * User: sunwu
 * Date: 2018/2/7
 * Time: 14:49
 */

namespace app\home\controller;

use app\home\def\Err;
use app\home\def\Helper;
use app\home\def\Search;
use app\home\model\ResourceCategory;
use think\captcha\Captcha;
use think\Controller;
use think\Cookie;
use think\Request;
use think\Url;

class Base extends Controller
{
    protected $err;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        Url::root('/index.php');
        $this->err = new Err();
    }

    /**
     * 验证码
     */
    public function vercode($id = '')
    {
        $captcha = new Captcha();
        return $captcha->entry($id);
    }

    /**
     * 文件上传
     */
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $saveName = "uploads/" . $info->getSaveName();
                $saveName = str_replace('\\', '/', $saveName);
                return $this->err->info(0, $saveName);
            } else {
                return $this->err->info(-1, $info->getError());
            }
        }
    }

    /**
     * 是否登录
     */
    protected function checkIsLogin()
    {
        if (empty(session('uid'))) {
            if (Request::instance()->isAjax()) {
                header("content-type:text/json");
                die(json_encode($this->err->info(-2)));
            } else {
                die("<script>location.href='" . url('login/login') . "'</script>");

            }

        };
        return '';

    }

    /**
     * 验证验证码api
     * @param $code
     * @param string $id
     * @return array
     */
    public function checkVercode($code, $id = '')
    {
        if (Helper::checkVercode($code, $id) === true) {
            return $this->err->info(0);
        } else {
            return $this->err->info(2);
        }
    }

    /**
     * 404页面
     * @return \think\response\View
     */
    public function err404()
    {
        return view('public/404');
    }

    /**
     * 提示页面
     * @param string $notice
     * @return \think\response\View
     */
    public function errNotice($notice = '')
    {
        $this->assign('notice', $notice);
        return view('public/notice');
    }

    /**
     * 发送邮件
     * @param $to
     * @param $title
     * @param $body
     * @return array
     */
    public function sendMail($to, $title, $body)
    {
        return Helper::sendMail($to, $title, $body);
    }

    /**
     * 详细搜索api
     * @return array
     */
    public function searchDetailApi()
    {

        $data = json_decode(input('post.search'), true);
        $keyword = $data['keyword'];
        Cookie::set('keyword', $keyword);
        $this->parseKeywords($keyword);
        $search = new Search($data);
        $searchData = $search->data();
        if ($searchData) {
            return $this->err->info(0, Helper::parseResData($searchData));
        } else {
            return $this->err->info(3);

        }
    }

    /**
     * 详细搜索
     * @param string $keyword
     * @return \think\response\View
     */
    public function search($keyword = '')
    {
        if ($keyword) Cookie::set('keyword', $keyword);
        $year = date("Y");
        $years = [];
        for ($i = 0; $i < 10; $i++) {
            $years[] = $year--;
        }
        $this->parseKeywords($keyword);
        $this->assign('years', $years);
        $this->assign('cats', (new ResourceCategory())->select());
        return view('public/search');
    }

    /**
     * 处理查询关键字
     * @param string $keyword
     */
    private function parseKeywords($keyword = '')
    {
        if ($keyword) {
            $keywordsArr = json_decode(Cookie::get('keywords'), true) ? json_decode(Cookie::get('keywords'), true) : [];;
            array_unshift($keywordsArr, $keyword);
            $keywordsArr = array_unique($keywordsArr);
            if (count($keywordsArr) > 10) {
                array_pop($keywordsArr);
            }
            Cookie::set('keywords', json_encode($keywordsArr));
            return;
        }
        return;
    }

    /**
     * 获取历史搜索记录
     */
    public function searchHistory()
    {
        return $this->err->info(0, $keywordsArr = json_decode(Cookie::get('keywords'), true) ? json_decode(Cookie::get('keywords'), true) : []);
    }

}